﻿@page "/settings/security/disable-2fa"
@using Microsoft.Extensions.Localization
@inherits MainBase
@inject HttpClient Http

<LayoutPageTitle>@Localizer["PageTitle"]</LayoutPageTitle>

@if (IsLoading)
{
    <LoadingIndicator />
}
else
{
    <div class="grid grid-cols-1 px-4 pt-6 xl:grid-cols-3 xl:gap-4 dark:bg-gray-900">
        <div class="mb-4 col-span-full xl:mb-2">
            <Breadcrumb BreadcrumbItems="BreadcrumbItems"/>
            <H1>@Localizer["PageTitle"]</H1>
            <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">@Localizer["PageDescription"]</p>
        </div>
    </div>

    <div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
        <AlertMessageError HasTopMargin="false" Message="@Localizer["WarningMessage"]" />
        <div class="mb-3 mt-4 text-sm text-gray-600 dark:text-gray-400">@Localizer["StatusMessage"]</div>
        <button @onclick="DisableTwoFactor"
                class="bg-red-500 text-white py-2 px-4 rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 transition duration-150 ease-in-out">
            @Localizer["ConfirmDisableButton"]
        </button>
    </div>
}

@code {
    private bool IsLoading { get; set; } = true;

    private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Pages.Settings.Security.Disable2Fa", "AliasVault.Client");

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = Localizer["BreadcrumbSecuritySettings"], Url = "/settings/security" });
        BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = Localizer["BreadcrumbDisable2Fa"] });
    }

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        // Check on server if 2FA is enabled
        if (firstRender)
        {
            var response = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("v1/TwoFactorAuth/status");
            if (response is not null && !response.TwoFactorEnabled)
            {
                GlobalNotificationService.AddErrorMessage(Localizer["TwoFactorNotEnabled"]);
                NavigationManager.NavigateTo("/settings/security");
                return;
            }

            IsLoading = false;
            StateHasChanged();
        }
    }

    private async Task DisableTwoFactor()
    {
        var response = await Http.PostAsync("v1/TwoFactorAuth/disable", null);
        if (response.IsSuccessStatusCode)
        {
            GlobalNotificationService.AddSuccessMessage(Localizer["TwoFactorDisabledSuccess"]);
            NavigationManager.NavigateTo("/settings/security");
            return;
        }

        // Handle error
        GlobalNotificationService.AddErrorMessage(Localizer["FailedToDisable2Fa"], true);
        StateHasChanged();
    }

    private sealed class TwoFactorEnabledResult
    {
        public required bool TwoFactorEnabled { get; init; } = false;
    }
}
